package com.businessportal.web.controllers.authenticate;

import com.businessportal.web.common.AuthHelper;
import com.businessportal.web.common.CryptoHelper;
import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.services.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created by Vadim on 11/27/14.
 */
@WebServlet(urlPatterns = "/securepages/email_confirmation.do")
public class ConfirmationController  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{

            String token = req.getParameter("token");

            String email = CryptoHelper.getInstance().decodeFromHex(token);

            Login user = UserService.INSTANCE.GetLoginByEmail(email);

            if(null != user){
                HttpSession session = req.getSession();

                String cookieText = AuthHelper.generateCookieToken(email);

                session.setAttribute("user", user);

                session.setMaxInactiveInterval(30*60);
                Cookie userName = new Cookie("user", cookieText);
                userName.setMaxAge(30*60);
                resp.addCookie(userName);

                user.setIsConfirmed(true);

                UserService.INSTANCE.UpdateUser(user);

                resp.sendRedirect("/securepages/admin_portal.do");
                return;
            }

        }catch(Exception e){
            System.out.println(e.getMessage());
        }

        resp.sendRedirect("/securepages/loginform.do");
    }
}
